package net.lzzy.service;

import net.lzzy.dao.CommentRepository;
import net.lzzy.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    public Comment findById(Integer id) {
        return commentRepository.findById(id).get();
    }

    public List<Comment> findAll() {
        return commentRepository.findAll();
    }

    public List<Comment> findAllSortByAID() {
        return commentRepository.findAll(Sort.by(Sort.Direction.DESC,"aId"));
    }

    //精确匹配查询 可多条件查询
    public List<Comment> findAllByAuthor1(String author) {
        Comment comment = new Comment();
        comment.setAuthor(author);
        Example<Comment> example = Example.of(comment);
        return commentRepository.findAll(example);
    }

    //模糊匹配查询
    public List<Comment> findAllByAuthor2(String author) {
        Comment comment = new Comment();
        comment.setAuthor(author);
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("author", ExampleMatcher.GenericPropertyMatcher::contains);
        Example<Comment> example = Example.of(comment, matcher);
        return commentRepository.findAll(example);
    }

    //分页查询
    public List<Comment> findAllPage(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return commentRepository.findAll(pageable).getContent();
    }

    public long count() {
        return commentRepository.count();
    }

    public Boolean exsitById(Integer id) {
        return commentRepository.existsById(id);
    }

    public Comment addComment(String author, String content, Integer aId) {
        Comment comment = new Comment();
        comment.setAuthor(author);
        comment.setContent(content);
        comment.setArticleId(aId);
        return commentRepository.save(comment);
    }

    public Comment updateComment(Integer id, String author, String content, Integer aId) {
        Comment comment = new Comment();
        comment.setId(id);
        comment.setAuthor(author);
        comment.setContent(content);
        comment.setArticleId(aId);
        return commentRepository.save(comment);
    }

    public void deleteCommentById(Integer id) {
        if (exsitById(id))
            commentRepository.deleteById(id);
    }

}
